﻿using System;
using System.ComponentModel;
using System.Linq;

namespace MadMediaManager.Core.ExtensionMethods
{
    public static class EnumExtensions
    {
        /// <summary>
        /// Get the <see cref="DescriptionAttribute"/> of an enum if one is available.  If one isn't available, <see cref="Enum.ToString()"/> is used.
        /// <para>See http://stackoverflow.com/questions/479410/enum-tostring</para>
        /// </summary>
        /// <param name="enumeration">The enum</param>
        /// <returns>The description</returns>
        public static string GetDescription(this Enum enumeration)
        {
            var type = enumeration.GetType();

            var enumString = enumeration.ToString();
            var fieldInfo = type.GetField(enumString);
            if (fieldInfo != null)
            {
                var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();

                if (attribute != null)
                {
                    // ReSharper disable PossibleNullReferenceException
                    return (attribute as DescriptionAttribute).Description;
                    // ReSharper restore PossibleNullReferenceException
                }
            }
            return enumString;
        }
    }
}
